<template>
  <div class="dialog">
    <el-dialog :visible.sync="isShow" width="40%" :show-close="false">
      <div slot="title" class="title">用户注册</div>
      <el-form
        :model="form"
        class="demo-ruleForm"
        :rules="rules"
        ref="form"
        label-width="70px"
      >
        <el-form-item prop="avatar" label="头像" class="upload-img">
          <el-upload
            class="avatar-uploader"
            name="image"
            :action="baseUrl + '/uploads'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.avatar"
              :src="baseUrl + '/' + form.avatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="昵称">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item prop="code" label="图形码">
          <el-row>
            <el-col :span="16">
              <el-input
                v-model="form.code"
                prefix-icon="el-icon-key"
              ></el-input>
            </el-col>
            <el-col :span="7" :offset="1">
              <img
                :src="baseUrl + '/' + codeUrl"
                alt=""
                class="code"
                @click="codeImgClick"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="rcode" label="验证码">
          <el-row>
            <el-col :span="16">
              <el-input
                v-model="form.rcode"
                prefix-icon="el-icon-key"
              ></el-input>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-button @click="btnrcode" :disabled="totalTime != 5"
                >获取验证码<span v-if="totalTime != 5">{{
                  totalTime
                }}</span></el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { register, btnsregister } from '../api/register'
export default {
  data () {
    return {
      isShow: false,
      totalTime: 5,
      baseUrl: process.env.VUE_APP_URL,
      codeUrl: '/captcha?type=sendsms',
      form: {
        avatar: '', //	是	string	头像地址
        username: '', //	是	string	用户名
        email: '', //	是	string	邮箱
        phone: '', //	是	string	手机号
        password: '', //	是	string	密码
        code: '',
        rcode: '' //	是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: '头像地址', trigger: 'blur' }],
        username: [{ required: true, message: '用户名', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的邮箱'))
              }
            }
          }
        ],
        phone: [
          { required: true, message: '手机号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确手机号'))
              }
            }
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '图形码', trigger: 'blur' }],
        rcode: [{ required: true, message: '验证码', trigger: 'blur' }]
      }
    }
  },
  // 侦听器清除表单
  watch: {
    isShow (newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields()
      }
    }
  },
  methods: {
    handleAvatarSuccess (res) {
      console.log(res)
      // this.imageUrl = res.data.file_path
      this.form.avatar = res.data.file_path
      this.$refs.form.validateField(['avatar'])
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 4

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或者png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 4MB!')
      }
      return isJPG && isLt2M
    },
    // 注册成功
    submit () {
      this.$refs.form.validate(ult => {
        if (ult) {
          this.$message.success('验证成功')
          btnsregister(this.form).then(res => {
            console.log('注册成功', res)
            this.$message.success('注册成功')
            this.isShow = false
          })
        } else {
          this.$message.error('验证失败')
        }
      })
    },
    // 点击图形码刷新
    codeImgClick () {
      this.codeUrl = '/captcha?type=sendsms&assa' + Date.now()
    },
    // 验证码
    btnrcode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], err => {
        // console.log('err', err)
        if (err == '') {
          num++
        }
        if (num == 2) {
          console.log(num)

          this.totalTime--
          let _interval = setInterval(() => {
            // 让总时间--
            this.totalTime--
            // 如果减到0,不要减了,变会总数
            if (this.totalTime == 0) {
              this.totalTime = 5
              // 清理倒计时
              clearInterval(_interval)
            }
          }, 1000)
          register({ code: this.form.code, phone: this.form.phone }).then(
            res => {
              console.log('验证码', res)
              this.$message.success(res.data.data.captcha + '')
            }
          )
        } else {
          // this.$message.error('请输入正确的图形码')
        }
      })
    }
  }
}
</script>
<style lang="less">
.dialog {
  .title {
    text-align: center;
    // background: linear-gradient();
    height: 53px;
    line-height: 53px;
    background: linear-gradient(to right, #01c4fa, #1395fa);
    color: #fff;
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__footer {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-img {
    text-align: center;
  }
  .code {
    width: 100%;
  }
}
</style>
